package cn.gzjp.modules.gas.web.api.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.config.Global;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.StringUtil;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.gas.entity.*;
import cn.gzjp.modules.gas.service.*;
import cn.gzjp.modules.gas.web.api.vo.OrderMonthVO;
import cn.gzjp.modules.it.api.bean.CommonJson;
import com.aliyuncs.exceptions.ClientException;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 微信小程序用户接口
 *
 *
 */
@Controller("gasController")
@Api(value = "加油站业务接口", description = "加油站业务接口")
@RequestMapping("${frontPath}/gas")
public class GasController extends BaseController {

	WxMaService wxService = GasWxService.getWxMaService();
    
    @Autowired
	private GasUserService gasUserService;
	@Autowired
	private GasStationService gasStationService;
	@Autowired
	private GasOrderService gasOrderService;
	@Autowired
	private GasGunService gasGunService;
	@Autowired
	private GasInvoiceService gasInvoiceService;
	@Autowired
	private GasCarService gasCarService;
	@Autowired
	private GasScoreService gasScoreService;

	@Autowired
	private GasRechargeService gasRechargeService;
    

	/**
	 * 登陆接口
	 */
	@ApiOperation(value = "用户登录新(返回的是sessionKey，要获得openid请接着调用info接口)")
	@RequestMapping(value = "login",method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="code",value="code",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String login(String code) {
		CommonJson result = new CommonJson();
		log.info("加油小程序用户微信登录 code="+code);
		if (StringUtils.isBlank(code)) {
			result.setMsg("code不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		try {
			WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
			String openid = session.getOpenid();
			if(StringUtils.isNotBlank(openid)){
				GasUser user = gasUserService.get(openid);
				if(user==null){
					user = new GasUser();
					user.setId(openid);
					user.setRegistTime(new Date());
					gasUserService.save(user);//新增用户
				}
			}
			log.info("openid="+openid+"|sessionKey="+session.getSessionKey());
			result.setData(session.getSessionKey());
			log.info("返回微信小程序"+mapper.toJson(result));
			return this.mapper.toJson(result);
		} catch (WxErrorException e) {
			this.logger.error(e.getMessage(), e);
			return e.toString();
		}
	}
    
    


	/**
	 * <pre>
	 * 获取用户信息接口
	 * </pre>
	 */

	@ApiOperation(value = "用户信息获取(新接口,后台可自动获取昵称和头像)")
	@RequestMapping(value = "info",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="sessionKey",value="会话密钥",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="encryptedData",value="消息密文",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="iv",value="加密算法的初始向量",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String info(String sessionKey,  String encryptedData, String iv) {
		CommonJson result = new CommonJson();
		log.info("加油小程序用户获取用户信息 sessionKey="+sessionKey+"|encryptedData="+encryptedData+"|iv="+iv);
		// 解密用户信息
		WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
		if(userInfo==null){
			result.setMsg("小程序获取用户信息失败");
			result.setCode(1);
			log.info(mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		GasUser user = gasUserService.get(userInfo.getOpenId());
		if(user==null){
			user = new GasUser();
			user.setRegistTime(new Date());
			user.setId(userInfo.getOpenId());

		}
		user.setNickName(userInfo.getNickName());
		user.setHeadImg(userInfo.getAvatarUrl());//用户头像
		gasUserService.save(user);//新增用户
		result.setData(user);

		log.info(mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	Map<String,Date> sendCodeMap = new HashMap<String,Date>();
	Map<String,String> mobileCodeMap = new HashMap<String,String>();

	/**
	 * 下发短信验证码
	 * @param mobile
	 * @return
	 */
	@ApiOperation(value = "验证码获取")
	@RequestMapping(value = "sendCode", method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="mobile",value="手机号",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String sendCode(String mobile) {
		CommonJson result = new CommonJson();
		log.info("获取验证码 mobile=" + mobile);
		if (cn.gzjp.common.utils.StringUtils.isBlank(mobile)) {
			result.setMsg("mobile参数不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		if (mobile.length() != 11) {
			result.setMsg("手机号长度不正确");
			result.setCode(2);
			return this.mapper.toJson(result);
		}
		Date sendDate = sendCodeMap.get(mobile);
		if (sendDate!=null&& DateUtils.addMinute(sendDate, 3)
				.after(new Date())) {//3分钟还没到期
			result.setCode(3);;
			result.setMsg("验证码已发送，3分钟内有效");;
			return this.mapper.toJson(result);
		}

		// 随机数的生成
		String randNum = StringUtil.getRandNum(4);
		String content=" 【智慧加油】您本次验证码为"+randNum+"，验证码请勿告知他人，非本人操作请忽略"  ;
		//SmsClientSend.sendSms(mobile, content);
		try {
		    AliyunSms.sendSms("智慧交管",mobile,randNum);
        }catch (ClientException e){
		    e.printStackTrace();
        }
		result.setData(randNum);
		mobileCodeMap.put(mobile, randNum);
		sendCodeMap.put(mobile, new Date());
        log.info("返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	/**
	 * 验证短信验证码
	 * @param mobile
	 * @param authCode
	 * @return
	 */
	@ApiOperation(value = "验证码验证")
	@RequestMapping(value = "verifyCode", method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="mobile",value="手机号",dataType="String",paramType="query",required =true),
			@ApiImplicitParam(name="authCode",value="验证码",dataType="String",paramType="query",required =true),
			@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String verifyCode(String mobile,String authCode,String openid) {
		CommonJson result = new CommonJson();
		log.info("验证短信验证码 mobile=" + mobile+"|验证码="+authCode);
		if (cn.gzjp.common.utils.StringUtils.isBlank(mobile)|| cn.gzjp.common.utils.StringUtils.isBlank(authCode)) {
			result.setMsg("参数不能为空");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if (mobile.length() != 11) {
			result.setMsg("手机号长度不正确");
			result.setCode(2);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}

		String randNum = mobileCodeMap.get(mobile);
		if("00000".equals(authCode.trim())|| cn.gzjp.common.utils.StringUtils.isNotBlank(randNum)&&authCode.trim().equals(randNum)){
			GasUser user = gasUserService.get(openid);
			user.setMobile(mobile);
			gasUserService.save(user);
			result.setCode(0);
			result.setMsg("验证成功");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}else{
			result.setCode(3);
			result.setMsg("验证码输入有误");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
		}
		return this.mapper.toJson(result);
	}


	/**
	 * <pre>
	 * 获取加油站信息
	 * </pre>
	 */

	@ApiOperation(value = "获取加油站信息")
	@RequestMapping(value = "getGasStation",method = RequestMethod.GET)
	@ResponseBody
	public String getGasStation() {
		CommonJson result = new CommonJson();
		log.info("获取加油站getGasStation()");
		GasStation station  = gasStationService.get("1");
		result.setData(station);
		log.info(mapper.toJson(result));
		return this.mapper.toJson(result);
	}


	@ApiOperation(value = "提交加油订单")
	@RequestMapping(value = "submitGasOrder",method = RequestMethod.POST)
	@ApiImplicitParams ({
			@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="gunId",value="油枪id",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="gasSingle",value="加油总量L",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="moneyTotal",value="总金额",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="orderPay",value="实际需要支付",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="gasWay",value="加油方式",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String submitGasOrder(String openid, String gunId, BigDecimal gasSingle,BigDecimal moneyTotal,BigDecimal orderPay,String gasWay) {
		CommonJson result = new CommonJson();
		log.info("提交加油订单 openid="+openid+"|gunId="+gunId+"|gasSingle="+gasSingle+"|moneyTotal="+moneyTotal+"|gasWay="+gasWay+"|orderPay="+orderPay);

		GasGun gasGun = gasGunService.get(gunId);
		if(gasGun==null){
			result.setMsg("编号为"+gunId+"的油枪不存在");
			result.setCode(-1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		GasOrder order = new GasOrder();
		order.setOpenid(openid);
		order.setStationId(gasGun.getStationId());
		order.setCategoryId(gasGun.getCategoryId());
		order.setGunSn(gasGun.getGunSn());
		order.setPrice(gasGun.getPrice());
		order.setTotalL(gasSingle);
		order.setTotalM(moneyTotal);
		order.setRealPayM(orderPay);
		order.setPayStatus(0);
		order.setGasway(gasWay);
		order.setDiscountM(order.getTotalM().subtract(order.getRealPayM()));
		gasOrderService.save(order);
		result.setData(order);
		log.info(mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "获取我的加油订单")
	@RequestMapping(value = "getGasOrders",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true)})
	@ResponseBody
	public String getGasOrders(String openid) {
		CommonJson result = new CommonJson();
		log.info("获取我的加油订单 openid="+openid);
		GasOrder order = new GasOrder();
		order.setOpenid(openid);
		order.setPayStatus(1);
		List<GasOrder> orderList = gasOrderService.findList(order);
		List<String> months = Lists.newArrayList();
		for(GasOrder gasOrder:orderList){
			if(!months.contains(gasOrder.getMonth())){
				months.add(gasOrder.getMonth());
			}
		}
		List<OrderMonthVO> orderMonthVOList = Lists.newArrayList();
		for(String month:months){
			List<GasOrder> monthOrderList = Lists.newArrayList();;
			for(GasOrder gasOrder:orderList){
				if(gasOrder.getMonth().equals(month)){
					monthOrderList.add(gasOrder);
				}
			}
			OrderMonthVO orderMonthVO = new OrderMonthVO();
			orderMonthVO.setMonth(month);
			orderMonthVO.setOrderList(monthOrderList);
			orderMonthVOList.add(orderMonthVO);
		}
		result.setData(orderMonthVOList);
		log.info(mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	/**
	 * <pre>
	 * 提交订单
	 * </pre>
	 */

	@ApiOperation(value = "提交充值订单")
	@RequestMapping(value = "submitRechargeOrder",method = RequestMethod.POST)
	@ApiImplicitParams ({
			@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="stationId",value="加油站编号",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="orderPay",value="充值金额(实际支付)",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="freeMoney",value="赠送金额",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String submitRechargeOrder(String openid, String stationId, BigDecimal orderPay, BigDecimal freeMoney) {
		CommonJson result = new CommonJson();
		log.info("提交充值订单 openid="+openid+"|stationId="+stationId+"|orderPay="+orderPay+"|freeMoney="+freeMoney);
		GasRecharge order = new GasRecharge();
		order.setOpenid(openid);
		//order.setStationId(stationId);
		order.setAmount(orderPay);
		order.setGive(freeMoney);
		order.setPayStatus(0);
		gasRechargeService.save(order);
		result.setData(order);
		log.info(mapper.toJson(result));
		return this.mapper.toJson(result);
	}


	/**
	 * 通过扫码获取加油枪信息
	 */
	@ApiOperation(value = "通过扫码获取加油枪信息")
	@RequestMapping(value = "getGunByScene",method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="scene",value="扫码后传到小程序页面的参数",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String getGunByScene(String scene) {
		CommonJson result = new CommonJson();
		log.info("通过扫码获取加油枪信息 scene="+scene);
		if (StringUtils.isBlank(scene)) {
			result.setMsg("scene不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		result.setData(gasGunService.get(scene));
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@Autowired
	private WxMyPayService wxPayService;
	/**
	 * 返回前台H5调用JS支付所需要的参数，公众号支付调用此接口
	 * @param orderId 订单id
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "微信支付所需参数")
	@RequestMapping(value = "getJSSDKPayInfo",method = RequestMethod.POST)
	@ApiImplicitParams ({
			@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="orderId",value="订单id",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="type",value="类型(1微信支付加油订单，2微信支付充值订单)",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String getJSSDKPayInfo(String openid,String orderId, HttpServletRequest request,String type) {
		log.info("getJSSDKPayInfo 拉起微信支付 orderId="+orderId+"|openid="+openid+"|type="+type);
		CommonJson result = new CommonJson();
		String appId = ConfigUtils.getProperty("appid2");
		String macid = ConfigUtils.getProperty("mchId");
		String key = ConfigUtils.getProperty("mchKey");
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
		String notifyUrl = basePath + Global.getFrontPath()+"/back/notify/" + type+"/"+orderId;
		String json="";
		if("1".equals(type)){
			GasOrder order = this.gasOrderService.get(orderId);
			if(order==null){
				result.setCode(-1);
				result.setMsg("订单不存在");
				log.info("返回微信小程序"+mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			String body = "加油"+order.getCategoryName()+order.getTotalL()+"L";
			json = this.wxPayService.getPayInfo(orderId,body,order.getRealPayM(), appId, macid, openid, request, key, notifyUrl,"");
		}
		else{
			GasRecharge order = this.gasRechargeService.get(orderId);
			if(order==null){
				result.setCode(-1);
				result.setMsg("订单不存在");
				log.info("返回微信小程序"+mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			String body = "加油充值"+order.getAmount()+"元";
			json = this.wxPayService.getPayInfo(orderId,body,order.getAmount(), appId, macid, openid, request, key, notifyUrl,"");
		}



		result.setData(json);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}



	@ApiOperation(value = "余额支付")
	@RequestMapping(value = "balancePay",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="orderId",value="加油订单id",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String balancePay(String orderId, HttpServletRequest request) {
		log.info("余额支付 orderId="+orderId);
		CommonJson result = new CommonJson();
		GasOrder order = this.gasOrderService.get(orderId);
		if(order==null){
			result.setCode(-1);
			result.setMsg("订单不存在");
			log.info("返回微信小程序"+mapper.toJson(result));
			return this.mapper.toJson(result);
		}

		GasUser gasUser = gasUserService.get(order.getOpenid());
		if(gasUser==null){
			result.setCode(-1);
			result.setMsg("会员不存在");
			log.info("返回微信小程序"+mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if(gasUser.getBalance().compareTo(order.getRealPayM())<0){
			result.setCode(1);
			result.setMsg("余额不足，无法支付");
			log.info("返回微信小程序"+mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		order.setPayStatus(1);
		gasOrderService.save(order);
		GasScore gasScore = new GasScore();
		gasScore.setOpenid(order.getOpenid());
		gasScore.setMemo("加油积分");
		gasScore.setScore(order.getTotalM().intValue());
		gasScoreService.save(gasScore);

		gasUser.setBalance(gasUser.getBalance().subtract(order.getRealPayM()));
		gasUser.setScoreCount(gasUser.getScoreCount()+order.getTotalM().intValue());
		gasUser.setGasCount(gasUser.getGasCount()+1);
		if(gasUser.getTotalL()==null) {
			gasUser.setTotalL(order.getTotalL());
		}else{
			gasUser.setTotalL(gasUser.getTotalL().add(order.getTotalL()));
		}
		if(gasUser.getTotalM()==null) {
			gasUser.setTotalM(order.getTotalM());
		}else{
			gasUser.setTotalM(gasUser.getTotalM().add(order.getRealPayM()));
		}
		gasUserService.save(gasUser);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}



	@ApiOperation(value = "微信支付成功回调(更新订单状态)")
	@RequestMapping(value = "wxPayOk",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="orderId",value="订单id",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="type",value="类型(1微信支付加油订单，2微信支付充值订单)",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String wxPayOk(String orderId, HttpServletRequest request,String type) {
		log.info("支付成功 orderId="+orderId+"|type="+type);
		CommonJson result = new CommonJson();
		if("1".equals(type)){//加油订单
			GasOrder order = this.gasOrderService.get(orderId);
			if(order==null){
				result.setCode(-1);
				result.setMsg("订单不存在");
				log.info("返回微信小程序"+mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			order.setPayStatus(1);
			GasScore gasScore = new GasScore();
			gasScore.setOpenid(order.getOpenid());
			gasScore.setMemo("加油积分");
			gasScore.setScore(order.getTotalM().intValue());
			gasScoreService.save(gasScore);
			gasOrderService.save(order);
			GasUser gasUser = gasUserService.get(order.getOpenid());
			gasUser.setDiscountM(gasUser.getDiscountM().add(order.getDiscountM()));
			gasUser.setScoreCount(gasUser.getScoreCount()+order.getTotalM().intValue());
			gasUser.setGasCount(gasUser.getGasCount()+1);
			if(gasUser.getTotalL()==null) {
				gasUser.setTotalL(order.getTotalL());
			}else{
				gasUser.setTotalL(gasUser.getTotalL().add(order.getTotalL()));
			}
			if(gasUser.getTotalM()==null) {
				gasUser.setTotalM(order.getTotalM());
			}else{
				gasUser.setTotalM(gasUser.getTotalM().add(order.getRealPayM()));
			}

			gasUserService.save(gasUser);
			result.setData(order);
		}else{
			//充值订单
			GasRecharge order = this.gasRechargeService.get(orderId);
			if(order==null){
				result.setCode(-1);
				result.setMsg("订单不存在");
				log.info("返回微信小程序"+mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			order.setPayStatus(1);
			gasRechargeService.save(order);
			GasUser gasUser = gasUserService.get(order.getOpenid());
			//gasUser.setScoreCount(gasUser.getScoreCount()+order.getAmount().intValue()+order.getGive().intValue());
			gasUser.setBalance(gasUser.getBalance().add(order.getAmount()).add(order.getGive()));//实际支付的加上赠送的
			gasUserService.save(gasUser);
			result.setData(order);
		}

		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}


	@ApiOperation(value = "获取我的发票")
	@RequestMapping(value = "getInvoices",method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String getInvoices(String openid) {
		log.info("获取我的发票 openid="+openid);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		GasInvoice search = new GasInvoice();
		search.setOpenid(openid);
		List<GasInvoice> gasInvoices = this.gasInvoiceService.findList(search);
		result.setData(gasInvoices);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "保存发票")
	@RequestMapping(value = "saveInvoice",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="title",value="发票抬头",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="taxpayerSn",value="纳税人识别号",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="mobile",value="手机号",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="address",value="单位地址",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="bankName",value="银行名称",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="bankAccount",value="银行账号",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String saveInvoice(String openid,String title,String taxpayerSn,String address,String mobile,String bankName,String bankAccount) {
		log.info("保存发票 openid="+openid+"|title="+title+"|taxpayerSn="+taxpayerSn);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		GasInvoice invoice = new GasInvoice();
		invoice.setOpenid(openid);
		invoice.setTitle(title);
		List<GasInvoice> gasInvoices = gasInvoiceService.findList(invoice);
		if(gasInvoices!=null&&gasInvoices.size()>0){
			result.setMsg("您已添加过该发票，无需重复添加");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		invoice.setTaxpayerSn(taxpayerSn);
		invoice.setAddress(address);
		invoice.setMobile(mobile);
		invoice.setBankName(bankName);
		invoice.setBankAccount(bankAccount);
		this.gasInvoiceService.save(invoice);
		result.setData(invoice);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "获取我的车辆")
	@RequestMapping(value = "getCars",method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String getCars(String openid) {
		log.info("获取我的车辆 openid="+openid);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		GasCar search = new GasCar();
		search.setOpenid(openid);
		List<GasCar> carList = this.gasCarService.findList(search);
		result.setData(carList);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "保存车辆")
	@RequestMapping(value = "saveCar",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="licensePlate",value="车牌",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String saveCar(String openid,String licensePlate) {
		log.info("保存车辆 openid="+openid+"|licensePlate="+licensePlate);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		GasCar car = new GasCar();
		car.setOpenid(openid);
		car.setLicensePlate(licensePlate);
		List<GasCar> carList = gasCarService.findList(car);
		if(carList!=null&&carList.size()>0){
			result.setMsg("您已添加过该车辆，无需重复添加");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		this.gasCarService.save(car);
		result.setData(car);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "删除车辆")
	@RequestMapping(value = "deleteCar",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="id",value="id",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String deleteCar(String id) {
		log.info("删除车辆 id="+id);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(id)) {
			result.setMsg("id不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		gasCarService.delete(gasCarService.get(id));
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "删除发票")
	@RequestMapping(value = "deleteInvoice",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="id",value="id",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String deleteInvoice(String id) {
		log.info("删除发票 id="+id);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(id)) {
			result.setMsg("id不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		gasInvoiceService.delete(gasInvoiceService.get(id));
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "获取我的积分列表")
	@RequestMapping(value = "getScoreList",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="startDate",value="开始时间(默认查近一个月)",dataType="java.util.Date",paramType="form",required =true),
			@ApiImplicitParam(name="endDate",value="截止时间(默认查近一个月)",dataType="java.util.Date",paramType="form",required =true)
	})
	@ResponseBody
	public String getScoreList(String openid,Date startDate,Date endDate) {
		log.info("获取我的积分列表 openid="+openid);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		GasScore search = new GasScore();
		search.setOpenid(openid);
//		if(startDate==null){
//			startDate = DateUtil.lastMonth();
//		}
//		if(endDate==null){
//			endDate = DateUtil.date();
//		}
//		search.setStartDate(startDate);
//		search.setEndDate(endDate);
		List<GasScore> scores = this.gasScoreService.findList(search);
		result.setData(scores);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}
	@Autowired
	private GasRechargeGiveService gasRechargeGiveService;

	@ApiOperation(value = "获取充值赠送规则列表")
	@RequestMapping(value = "getRechargeGiveList",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String getRechargeGiveList(String openid) {
		log.info("获取充值赠送规则列表 openid="+openid);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}

		List<GasRechargeGive> gasRechargeGives = gasRechargeGiveService.findList(new GasRechargeGive());
		result.setData(gasRechargeGives);
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	@ApiOperation(value = "根据id获取订单信息")
	@RequestMapping(value = "getOrderById",method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="orderId",value="订单id",dataType="String",paramType="form",required =true),
			@ApiImplicitParam(name="type",value="类型(1微信支付加油订单，2微信支付充值订单)",dataType="String",paramType="form",required =true)
	})
	@ResponseBody
	public String getOrderById(String orderId, HttpServletRequest request,String type) {
		log.info("根据id获取订单信息 orderId="+orderId+"|type="+type);
		CommonJson result = new CommonJson();
		if("1".equals(type)){
			GasOrder order = this.gasOrderService.get(orderId);
			if(order==null){
				result.setCode(-1);
				result.setMsg("订单不存在");
				log.info("返回微信小程序"+mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			result.setData(order);
		}else{
			GasRecharge order = this.gasRechargeService.get(orderId);
			if(order==null){
				result.setCode(-1);
				result.setMsg("订单不存在");
				log.info("返回微信小程序"+mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			result.setData(order);
		}
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}
	/**
	 * 个人信息
	 */
	@ApiOperation(value = "个人信息")
	@RequestMapping(value = "myInfo",method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="query",required =true)
	})
	@ResponseBody
	public String myInfo(String openid) {
		CommonJson result = new CommonJson();
		log.info("个人信息 openid=" + openid);
		if (StringUtils.isBlank(openid)) {
			result.setMsg("openid不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		result.setData(gasUserService.get(openid));
		log.info("返回微信小程序"+mapper.toJson(result));
		return this.mapper.toJson(result);
	}

}
